import React, { FC, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Checkbox, Form, Input, Card, Space } from 'antd'
import styles from './index.module.scss'
import { loginAPI } from '@/server/user'
import { useDispatch } from 'react-redux'
import { loginReducer } from '@/store/userReducer'

type FieldType = {
  username: string
  password: string
  remember: boolean
}

const Login: FC = () => {
  const router = useNavigate()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const onSubmit = async (values: any) => {
    if (values.remember) {
      window.localStorage.setItem('userinfo', JSON.stringify(values))
    } else {
      window.localStorage.removeItem('userinfo')
    }
    const res = await loginAPI(values)
    dispatch(loginReducer(res.data))
    router('/')
  }
  useEffect(() => {
    const userinfo = window.localStorage.getItem('userinfo')
    if (userinfo) {
      form.setFieldsValue(JSON.parse(userinfo))
    }
  }, [form])
  return (
    <div className={styles.container}>
      <Card
        title="登录"
        bordered={false}
        style={{ width: 500 }}
        headStyle={{ textAlign: 'center' }}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 500 }}
          initialValues={{ remember: true }}
          onFinish={onSubmit}
          form={form}
          autoComplete="off">
          <Form.Item<FieldType>
            label="账号"
            name="username"
            rules={[{ required: true, message: '请输入!' }]}>
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入!' }]}>
            <Input.Password />
          </Form.Item>

          <Form.Item<FieldType>
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 8, span: 16 }}>
            <Checkbox>记住密码</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Button type="primary" onClick={() => router('/register')}>
                注册
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
